#pragma once
#include<iostream>
#include<pthread.h>
#include<signal.h>
#include"Sock.hpp"
#include"TcpServer.hpp"
#include"Protocol.hpp"
#include"ThreadPool.hpp"
#include"Task.hpp"
#include"Log.hpp"

#define PORT 8081

//上层的Http服务端
class HttpServer
{
private:
    int port;
    int num;
    TcpServer* tcp;
    ThreadPool* tp;
    static bool stop;
public:
    HttpServer(int _port=PORT,int _num=NUM):port(_port),num(_num){}
    void InitHttpServer()
    {
        signal(SIGPIPE,SIG_IGN);//忽略信号-避免写入错误导致服务器关闭
        tcp=TcpServer::getInstance(port);
        tp=ThreadPool::getInstance(num);
    }
    void Loop()
    {
        int listen_sock=tcp->Sock();
        LOG(INFO,"Loop Begin");
        while(!stop)
        {
            int sock=Sock::Accept(listen_sock);
            if(sock<0)
                continue;
            //1.多线程处理连接
            // int* sk=new int(sock);
            // pthread_t tid;
            // pthread_create(&tid,nullptr,Entance::HandlerRequest,sk);
            // pthread_detach(tid);
            //2.线程池处理
            LOG(INFO,"Get A New Link");
            Task* t=new Task(sock);
            LOG(INFO,"New Task");
            tp->Put(t);
            LOG(INFO,"Put Task");
        }
        LOG(INFO,"Loop End");
    }
};
bool HttpServer::stop=false;